package com.fly.demo.controller;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import com.fly.demo.sse.SSEServer;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
public class DataPushController
{
    long i = 0L;
    
    @CrossOrigin
    @GetMapping("/sse/connect/{userId}")
    public SseEmitter connect(@PathVariable String userId)
    {
        return SSEServer.connect();
    }
    
    /**
     * 初始化触发
     */
    @PostConstruct
    private void init()
    {
        log.info("Server-Sent Events start");
        new ScheduledThreadPoolExecutor(2).scheduleAtFixedRate(() -> {
            SSEServer.batchSendMessage(RandomStringUtils.randomAlphanumeric(10));
        }, 2000, 1000, TimeUnit.MILLISECONDS);
    }
}
